package com.yuyou.fn.common.service.impl;

import cn.emay.sdk.client.api.Client;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.common.entity.Sms;
import com.yuyou.fn.common.mapper.SmsMapper;
import com.yuyou.fn.common.service.ISiteConfigService;
import com.yuyou.fn.common.service.ISmsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Sms 表数据服务层接口实现类
 */
@Service
public class SmsServiceImpl extends SuperServiceImpl<SmsMapper, Sms, Long> implements ISmsService {

    @Resource
    private ISiteConfigService siteConfigService;

    @Value("${dev.env}")
    private boolean dev;

    @Override
    public boolean sendCode(String phoneNo) {
        Example<Sms> smsExample = Sms.createExample();
        Example.Criteria criteria = smsExample.createCriteria();
        criteria.andEqualTo("smsType", 1).andEqualTo("phoneNo", phoneNo);
        smsExample.orderBy("createTime").desc();
        Sms sms = findOneByExample(smsExample);

        if (sms == null || (new Date().getTime() - sms.getCreateTime().getTime()) > 1 * 60 * 1000) {
            try {
                String[] phoneNos = new String[]{phoneNo};
                String code = "999999";
                String smsSpiNo = siteConfigService.getConfigValueFromCache("sms_spi_no");
                String smsSpiPassword = siteConfigService.getConfigValueFromCache("sms_spi_password");

                Client client = new Client(smsSpiNo, smsSpiPassword);
                int sendResult = 0;
                if (!dev) {
                    code = RandomStringUtils.randomNumeric(6);
                    String content = String.format("您的验证码为：%s，此验证码有效时长为30分钟，如非本人操作，请忽略此短信。", code);
                    sendResult = client.sendSMS(phoneNos, content, 3);
                }

                if (sendResult == 0) {
                    Sms nSms = new Sms();
                    nSms.setContent(code);
                    nSms.setSmsType(1);
                    nSms.setPhoneNo(phoneNo);
                    Date now = new Date();
                    nSms.setCreateTime(now);
                    nSms.setUpdateTime(now);
                    insert(nSms);
                } else {
                    return false;
                }


            } catch (Exception e) {
                throw new RuntimeException("sms not available", e);
            }
        }

        return true;
    }

    @Override
    public boolean validate(String phoneNo, String code) {

        if (dev) {
            return true;
        }

        Example<Sms> smsExample = Sms.createExample();
        Example.Criteria criteria = smsExample.createCriteria();
        criteria.andEqualTo("smsType", 1).andEqualTo("phoneNo", phoneNo).andEqualTo("content", code);
        smsExample.orderBy("createTime").desc();
        Sms sms = findOneByExample(smsExample);
        if (sms == null || (new Date().getTime() - sms.getCreateTime().getTime()) > 30 * 60 * 1000) {
            return false;
        }

        return true;
    }

    @Override
    public boolean send(List<String> phoneNoList, String msg) throws Exception {
        String[] phoneNos = phoneNoList.toArray(new String[phoneNoList.size()]);
        String smsSpiNo = siteConfigService.getConfigValueFromCache("sms_spi_no");
        String smsSpiPassword = siteConfigService.getConfigValueFromCache("sms_spi_password");
        Client client = new Client(smsSpiNo, smsSpiPassword);
        int sendResult = 0;
        if (!dev) {
            sendResult = client.sendSMS(phoneNos, msg, 3);
        }

        if (sendResult == 0) {

            List<Sms> smsList = new ArrayList<>(phoneNoList.size());

            Date now = new Date();
            for (String p : phoneNoList) {
                Sms nSms = new Sms();
                nSms.setContent(msg);
                nSms.setSmsType(2);
                nSms.setPhoneNo(p);
                nSms.setCreateTime(now);
                nSms.setUpdateTime(now);
                smsList.add(nSms);
            }
            insertBatch(smsList);
            return true;
        } else {
            return false;
        }
    }
}